// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.1

package user

import (
	"audio-server/internal/model"
	"audio-server/internal/sqlutil"
	"context"
	"encoding/json"
	"errors"

	"audio-server/internal/svc"
	"audio-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserDetailLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserDetailLogic {
	return &UserDetailLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserDetailLogic) UserDetail(req *types.UserDetailReq) (resp *types.UserDetailResp, err error) {
	id := req.Id
	usersModel := model.NewUsersModel(l.svcCtx.Conn)
	user, err := usersModel.FindOne(l.ctx, id)
	if err != nil {
		return nil, errors.New("用户不存在")
	}
	userResp := types.UserDetailResp{
		Id:          user.Id,
		Username:    user.Username,
		Nickname:    user.Nickname,
		Avatar:      user.Avatar,
		Gender:      int(user.Gender),
		Description: sqlutil.NullStringToString(user.Description),
	}
	roleIds := user.RoleIds
	var strSlice []int
	err = json.Unmarshal([]byte(roleIds), &strSlice)
	if err == nil {
		if len(strSlice) != 0 {
			userResp.RoleIds = strSlice
		}
	}

	return &userResp, nil

}
